package books4africa

import grails.converters.XML

class BooksException extends RuntimeException{
	String message
	String book
}

class ValidationException extends RuntimeException{
	String message
	String book
	
}


class BooksService {

    def springSecurityService
	boolean transactional = true
	
	def saveBook(params){
		def bookInstance = new Books(params)
		
		if (!bookInstance.save(flush:true)){
			throw new BooksException(
				message: "Unable to save book",
				book: bookInstance.errors.each{println it}
			)
		}
		
		return bookInstance
	}
	
	def saveBookRest(request) {
		//def xml = request.XML
		def book = new Books()
		
		book.title= request.XML.title.text()
		book.author= request.XML.author.text()
		book.description = request.XML.description.text()
		book.isbn = request.XML.isbn.text()
		book.category = request.XML.category.text()
		
		book.edition = request.XML.edition.text().toInteger()
		book.minGradeLevel = request.XML.minGradeLevel.text().toInteger()
		book.maxGradeLevel = request.XML.maxGradeLevel.text().toInteger()
		
		if (book.validate()){
			book.save()
			response.status = 201
			render ""
		} 
	}
	
	
	def updateBook(params){
		def instance = Books.get(params.id)
		
		if (!instance){
			throw new BooksException(
				message:"Unable to retrieve book ${params.title}",
				book: instance.errors.each{println it}
			)
		}
		
		if (instance.version > params.version){
			throw new ValidationException(
				message: "Locking Failure: Another User has updated while you were editing",
				book: instance.errors.each{println it}
			)
		}
		
		instance.properties = params
		
		return instance
	}
	
	def restUpdate(request){
		def book = new Books()
		
		book.title= request.XML.title.text()
		book.author= request.XML.author.text()
		book.description = request.XML.description.text()
		book.isbn = request.XML.isbn.text()
		book.category = request.XML.category.text()
		
		book.edition = request.XML.edition.text().toInteger()
		book.minGradeLevel = request.XML.minGradeLevel.text().toInteger()
		book.maxGradeLevel = request.XML.maxGradeLevel.text().toInteger()
		
		if (book.validate()){
			book.save()
			response.status = 201
			render ""
		} else {
			response.status = 403
		}
	}
	
}
